package com.powernode.filter;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.config.WhiteUrlsConfig;
import com.powernode.constant.AuthConstants;
import com.powernode.constant.BusinessEnum;
import com.powernode.constant.HttpConstants;
import com.powernode.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/*
* 全局token过滤器(验证token)
* 前后端约定好的令牌存放位置，authorization bearer token
* */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {


    @Resource
    private WhiteUrlsConfig whiteUrlsConfig;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 校验token
     * 1.获取请求路径
     * 2.判断是否能放行
     * @param exchange 上下文
     * @param chain 过滤器链
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取请求路径
        String path = request.getPath().toString();
        //3.判断 是否再白名单
        if (whiteUrlsConfig.getAllowUrls().contains(path)){
            return chain.filter(exchange);
        }

        //3.1.不在白名单获取请求头 从 authorization 获取到的字符串的格式：bearer token
        String authorizationValue = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);
        //4.判断是否为空 hasText判断是否为null、长度是否为0、是否是空格等空白字符，都为否才返回true
        //boolean b = StringUtils.hasText(authorizationValue);
        if (StrUtil.isNotBlank(authorizationValue)) {
            //4.1.非空，获取token
            String token = authorizationValue.replaceFirst(AuthConstants.BEARER, "");
            //4.2.判断token是否未空，以及redis里token是否存在
            if (StrUtil.isNotBlank(token) &&
                    Boolean.TRUE.equals(
                            stringRedisTemplate.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX + token) )){
                //token有值并且redis里存在，身份验证通过
                return chain.filter(exchange);
            }
        }

        //身份不合法或请求非法
        log.error("拦截非法请求，时间：{}，请求API路径：{}", LocalDateTime.now(),path);

        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置响应头信息
        response.getHeaders().set(HttpConstants.CONTENT_TYPE,HttpConstants.APPLICATION_JSON);

        //设置响应信息
        Result<Object> result = Result.fail(BusinessEnum.UN_AUTHORIZATION);

        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes;
        try {
            bytes = objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataBuffer wrap = response.bufferFactory().wrap(bytes);

        return response.writeWith(Mono.just(wrap));
    }



    @Override
    public int getOrder() {
        return 0;
    }
}
